package connect;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;

import com.example.administrator.bluetoothdemo01.util.Constant;

import java.io.IOException;
import java.util.UUID;

/**
 * Created by Lzz on 8/5/2017.
 *
 *
 *
 * 客户端连接
 *
 */

public class ConnectThread extends Thread {

    private final static UUID MY_UUID = UUID.fromString(Constant.CONNECTTION_UUII);
    private final BluetoothSocket mBluetoothSocket;
    private final BluetoothDevice mDevice;
    private final BluetoothAdapter mBluetoothAdapter;
    private final Handler mHandler;
    private ConnectedThread mConnectedThread;

    public ConnectThread(BluetoothDevice device, BluetoothAdapter bluetoothAdapter, Handler handler) {
        BluetoothSocket tmp = null;
        mDevice = device;
        mHandler = handler;
        mBluetoothAdapter = bluetoothAdapter;
        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mBluetoothSocket = tmp;
    }

    @Override
    public void run() {

        // 连接前 把搜索设备动作 关掉
        mBluetoothAdapter.cancelDiscovery();

        try {
            mBluetoothSocket.connect();
        } catch (IOException e) {
            e.printStackTrace();
            mHandler.sendMessage(mHandler.obtainMessage(Constant.MSG_DATA_ERROR, e));

            try {
                mBluetoothSocket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return;
        }
        manageConnectedSocket(mBluetoothSocket);

    }

    // 管理连接
    private void manageConnectedSocket(BluetoothSocket bluetoothSocket) {
        mHandler.sendEmptyMessage(Constant.MSG_CONNECTED_TO_SERVER);
        mConnectedThread = new ConnectedThread(bluetoothSocket, mHandler);
        mConnectedThread.start();
    }

    // 取消连接
    public void cancel() {
        try {
            mBluetoothSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //写操作
    public void sendData(byte[] bytes) {
        if (mConnectedThread != null) {
            mConnectedThread.write(bytes);
        }
    }


}
